package cn.tedu.submarine;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 表示整个游戏窗口
 */
public class World extends JPanel {

    public static final int WIDTH = 641;//窗口的宽
    public static final int HEIGHT = 479;//窗口的高
    public static final int RUNNING = 0;//运行状态
    public static final int GAME_OVER = 1;//结束状态
    public static final int PAUSE = 2;//暂停状态
    private int currentState = RUNNING;//当前状态

    private Battleship ship = new Battleship();
    private SeaObject[] submarines = {};//潜艇数组
    private Bomb[] bombs = {};
    private Mine[] mines = {};

    private int score = 100;//玩家得分

    private SeaObject nextSubmarine() {
        Random random = new Random();
        int type = random.nextInt(100);
        if (type < 30) {
            return new TorpedoSubmarine();
        } else if (type < 75) {
            return new ObserveSubmarine();
        } else {
            return new MineSubmarine();
        }
    }

    /**
     * 检测游戏结束
     */
    private void checkGameOverAction() {
        if (ship.getLife() <= 0 || (score <= 0 && bombs.length == 0)) {
            currentState = GAME_OVER;
        }
    }

    /**
     * 水雷和战舰碰撞
     */
    private void mineBangAction() {
        for (int i = 0; i < mines.length; i++) {
            if (mines[i].isLive() && ship.isLive() && mines[i].isHit(ship)) {
                mines[i].goDead();
                ship.subtractLife();
            }
        }
    }

    /**
     * 炸弹和潜艇碰撞
     */
    private void bombBangAction() {
        for (int i = 0; i < submarines.length; i++) {
            for (int j = 0; j < bombs.length; j++) {
                if (submarines[i].isLive() && bombs[j].isLive() && submarines[i].isHit(bombs[j])) {
                    submarines[i].goDead();
                    bombs[j].goDead();
                    if (submarines[i] instanceof EnemyScore) {//潜艇为得分潜艇
                        score += ((EnemyScore) submarines[i]).getScore();//玩家得分
                    }
                    if (submarines[i] instanceof EnemyLife) {//潜艇为得命潜艇
                        ship.addLife(((EnemyLife) submarines[i]).getLife());//战舰增命
                    }
                }
            }
        }
    }

//    private void bombHitSubmarineAction(){
//        for (int i = 0; i < submarines.length; i++) {
//            for (int j = 0; j < bombs.length; j++) {
//                if (submarines[i].isHit(bombs[j])){
//                    submarines[i] = submarines[submarines.length-1];//将越界元素替换为最后一个元素
//                    submarines = Arrays.copyOf(submarines,submarines.length-1);//缩容，将重复的最后一个元素删除
//                    bombs[j] = bombs[bombs.length-1];//将越界元素替换为最后一个元素
//                    bombs = Arrays.copyOf(bombs,bombs.length-1);//缩容，将重复的最后一个元素删除
//                }
//            }
//        }
//    }

    private int subEnterIndex = 0;

    //潜艇入场
    private void submarineEnterAction() {//和action一样  十毫秒走一次
        subEnterIndex++;
        if (subEnterIndex % 35 == 0) {//控制每0.35秒(350毫秒)走一次
            SeaObject obj = nextSubmarine();
            submarines = Arrays.copyOf(submarines, submarines.length + 1);//数组扩容，再将obj存入数组
            submarines[submarines.length - 1] = obj;
        }
    }

    private int mineEnterIndex = 0;

    //水雷入场
    private void mineEnterAction() {//和action一样  十毫秒走一次
        mineEnterIndex++;
        if (mineEnterIndex % 100 == 0) {
            for (int i = 0; i < submarines.length; i++) {
                if (submarines[i] instanceof MineSubmarine) {
                    MineSubmarine ms = (MineSubmarine) submarines[i];//向下转型，方便使用shootMine
                    Mine obj = ms.shootMine();//获取水雷对象
                    mines = Arrays.copyOf(mines, mines.length + 1);
                    mines[mines.length - 1] = obj;
                }
            }
        }
    }

    //移动
    private void moveAction() {//和action一样  十毫秒走一次
        for (int i = 0; i < submarines.length; i++) {
            submarines[i].move();
        }
        for (int i = 0; i < mines.length; i++) {
            mines[i].move();
        }
        for (int i = 0; i < bombs.length; i++) {
            bombs[i].move();
        }
    }

    //删除越界的海洋对象
    private void outOfBoundsAction() {
        for (int i = 0; i < submarines.length; i++) {
            if (submarines[i].isOutOfBounds() || submarines[i].isDead()) {//越界或者死了的
                submarines[i] = submarines[submarines.length - 1];//将越界元素替换为最后一个元素
                submarines = Arrays.copyOf(submarines, submarines.length - 1);//缩容，将重复的最后一个元素删除
            }
        }
        for (int i = 0; i < bombs.length; i++) {
            if (bombs[i].isOutOfBounds() || bombs[i].isDead()) {
                bombs[i] = bombs[bombs.length - 1];//将越界元素替换为最后一个元素
                bombs = Arrays.copyOf(bombs, bombs.length - 1);//缩容，将重复的最后一个元素删除
            }
        }
        for (int i = 0; i < mines.length; i++) {
            if (mines[i].isOutOfBounds() || mines[i].isDead()) {
                mines[i] = mines[mines.length - 1];//将越界元素替换为最后一个元素
                mines = Arrays.copyOf(mines, mines.length - 1);//缩容，将重复的最后一个元素删除
            }
        }
    }

    /* 启动程序的执行 */
    private void action() {
        KeyAdapter k = null;
        /* 侦听器 */
        if (currentState == RUNNING) {
            k = new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    super.keyPressed(e);
                    if (e.getKeyCode() == KeyEvent.VK_P) {//若按下的是P则变为暂停状态
                        if (currentState == RUNNING) {
                            currentState = PAUSE;
                        } else if (currentState == PAUSE) {
                            currentState = RUNNING;
                        }
                    }

                    if (score > 0) {
                        if (e.getKeyCode() == KeyEvent.VK_DOWN) {//我按下的是向下键
                            Bomb obj = ship.shootBomb();//战舰发射炸弹
                            bombs = Arrays.copyOf(bombs, bombs.length + 1);
                            bombs[bombs.length - 1] = obj;
                            score -= 10;//每一个炸弹都需要消耗10分
                        }
                    }

                    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                        ship.moveLeft();
                    }
                    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                        ship.moveRight();
                    }
                }
            };
        }
        this.addKeyListener(k);

        /* 定时器 */
        Timer timer = new Timer();//定时器对象
        int interval = 10;
        //定时启动，每多长时间就会启动
        timer.schedule(new TimerTask() {
            @Override
            public void run() {//定时任务
                if (currentState == RUNNING) {
                    submarineEnterAction();//潜艇入场
                    mineEnterAction();//水雷入场
                    moveAction();//海洋对象移动
                    outOfBoundsAction();//删除越界的海洋对象
                    bombBangAction();
                    mineBangAction();
                    checkGameOverAction();
//                bombHitSubmarineAction();
//                System.out.println(submarines.length + "," +bombs.length+ "," +mines.length);
                    repaint();//重画----自动调用paint()方法
                }
            }
        }, interval, interval);

    }


    public void paint(Graphics graphics) {
        Images.sea.paintIcon(null, graphics, 0, 0);//画海洋图
        ship.paintImage(graphics);
        for (int i = 0; i < submarines.length; i++) {
            submarines[i].paintImage(graphics);
        }
        for (int i = 0; i < bombs.length; i++) {
            bombs[i].paintImage(graphics);
        }
        for (int i = 0; i < mines.length; i++) {
            mines[i].paintImage(graphics);
        }

        graphics.drawString("SCORE: " + score, 200, 50);
        graphics.drawString("LIFE: " + ship.getLife(), 400, 50);

        if (currentState == GAME_OVER) {
            Images.gameover.paintIcon(null, graphics, 0, 0);
        }
    }


    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setTitle("XmGXL的潜艇大战");
        World world = new World();//会创建World类中的所有的成员变量
        world.setFocusable(true);
        frame.add(world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH + 16, HEIGHT + 39);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);//自动调用paint()方法

        //启动程序的执行
        world.action();

    }

}
